# 导入必要的模块
from PyQt5.QtWidgets import *
import sys
from ui import untitled  # 导入由 Qt Designer 生成的 UI 文件
import json  # 用于读写配置文件
import os  # 用于判断文件是否存在

# -------------------------------------------------
# 工具：读取/保存配置
# -------------------------------------------------

# 定义配置文件名
SETTINGS_FILE = "settings.json"


def load_settings():
    """
    加载配置文件。如果文件不存在，则创建一个默认配置。
    返回配置字典。
    """
    if not os.path.exists(SETTINGS_FILE):
        save_settings({"ip": "127.0.0.1", "port": 5000})  # 默认配置
    with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
        return json.load(f)


def save_settings(cfg):
    """
    将配置字典保存到 JSON 文件中。
    cfg: 配置字典
    """
    with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
        json.dump(cfg, f, indent=4)  # 格式化输出，便于阅读


# -------------------------------------------------
# 设置对话框类
# -------------------------------------------------
class SettingsDialog(QDialog):
    """
    弹出设置窗口，允许用户修改服务器 IP 和端口。
    """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("服务器设置")
        self.resize(300, 150)

        # 加载当前配置
        cfg = load_settings()

        # 创建输入框并填充当前配置
        self.ip_edit = QLineEdit(cfg["ip"])
        self.port_edit = QLineEdit(str(cfg["port"]))

        # 使用垂直布局管理器
        form = QVBoxLayout(self)
        form.addWidget(QLabel("IP 地址："))
        form.addWidget(self.ip_edit)
        form.addWidget(QLabel("端口："))
        form.addWidget(self.port_edit)

        # 按钮布局
        btn_layout = QHBoxLayout()
        ok_btn = QPushButton("确定")
        ok_btn.clicked.connect(self.accept)
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        btn_layout.addWidget(ok_btn)
        btn_layout.addWidget(cancel_btn)
        form.addLayout(btn_layout)

    def accept(self):
        """
        点击“确定”按钮时验证输入并保存配置。
        """
        ip = self.ip_edit.text().strip()
        port = self.port_edit.text().strip()

        # 输入验证
        if not ip or not port.isdigit():
            QMessageBox.warning(self, "错误", "请输入有效的 IP 和端口！")
            return

        # 保存配置
        save_settings({"ip": ip, "port": int(port)})
        super().accept()  # 关闭对话框


# -------------------------------------------------
# 主窗口类
# -------------------------------------------------
class UI_main_1(QMainWindow):
    """
    主界面窗口，包含多个功能按钮和设置按钮。
    """

    def __init__(self):
        super().__init__()
        self.ui = untitled.Ui_MainWindow()
        self.ui.setupUi(self)

        # 连接按钮点击事件
        self.ui.pushButton.clicked.connect(self.go_to_main_2)  # 图片处理
        self.ui.pushButton_2.clicked.connect(self.go_to_main_3)  # 视频处理
        self.ui.pushButton_4.clicked.connect(self.exit)  # 退出程序
        self.ui.pushButton_3.clicked.connect(self.go_to_main_4)  # 摄像头处理

        # 新增设置按钮
        self.ui.pushButton_settings = QPushButton("设置")
        self.ui.pushButton_settings.setStyleSheet(
                """
                QPushButton{
                    background-color: #5d8a6a; color: #ffffff;
                    font-family: "PingFang SC"; font-size: 18px;
                    padding: 10px 20px; border: none; border-radius: 5px;
                }
                QPushButton:hover{ background-color: #4a6f55; }
                """
                )
        self.ui.pushButton_settings.clicked.connect(self.open_settings)

        # 添加设置按钮到左侧按钮区域（假设是 verticalLayout_2）
        self.ui.verticalLayout_2.addWidget(self.ui.pushButton_settings)

        # 初始化子窗口为 None
        self.pic_window = None
        self.vid_window = None
        self.cam_window = None

        self.show()

    def go_to_main_2(self):
        """跳转到图片处理窗口"""
        self.close_video_window()

        from picture import ImageWindow

        self.pic_window = ImageWindow()
        self.pic_window.show()
        self.hide()

    def go_to_main_3(self):
        """跳转到视频处理窗口"""
        self.close_video_window()

        from video import MainWindow

        self.vid_window = MainWindow()

        # 如果视频窗口被销毁，调用回调函数
        if hasattr(self.vid_window, 'destroyed'):
            self.vid_window.destroyed.connect(self.on_video_window_closed)

        self.vid_window.show()
        self.hide()

    def go_to_main_4(self):
        """跳转到摄像头处理窗口"""
        self.close_video_window()

        from camera import MainWindow

        self.cam_window = MainWindow()
        self.cam_window.show()
        self.hide()

    def exit(self):
        """退出程序，关闭所有子窗口"""
        self.close_video_window()
        self.close_picture_window()
        self.close_camera_window()
        self.close()

    def close_video_window(self):
        """安全关闭视频窗口并释放资源"""
        if self.vid_window and not self.vid_window.isHidden():
            if hasattr(self.vid_window, 'cleanup_before_close'):
                self.vid_window.cleanup_before_close()
            self.vid_window.close()
            self.vid_window = None

    def close_picture_window(self):
        """关闭图片窗口"""
        if self.pic_window and not self.pic_window.isHidden():
            self.pic_window.close()
            self.pic_window = None

    def close_camera_window(self):
        """关闭摄像头窗口"""
        if self.cam_window and not self.cam_window.isHidden():
            self.cam_window.close()
            self.cam_window = None

    def on_video_window_closed(self):
        """视频窗口关闭后的回调函数"""
        self.vid_window = None
        self.show()  # 显示主窗口

    def open_settings(self):
        """打开设置对话框"""
        dlg = SettingsDialog(self)
        dlg.exec_()


# 程序入口
if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = UI_main_1()
    sys.exit(app.exec_())
